package com.supermarket.manage.business.auth.service;

import com.supermarket.manage.common.constant.CodeConstant;
import com.supermarket.manage.common.pojo.MyUser;
import com.supermarket.manage.common.pojo.Permission;
import com.supermarket.manage.common.utils.TimeUtil;
import com.supermarket.manage.provider.api.ucenter.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Faxon
 * @version 1.0
 * @date 2020-02-13 10:59
 **/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Reference(version = "1.0.0")
    private UserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        MyUser myUser = null;
        //验证码模式
        String prefix = CodeConstant.PHONE_PREFIX + TimeUtil.getNowData();
        if (username.startsWith(prefix)) {
            myUser = userService.getUserByUsername(username.replaceFirst(prefix, ""));
            String code = stringRedisTemplate.opsForValue().get(CodeConstant.CODE_PREFIX + myUser.getPhone());
            if (StringUtils.isBlank(code)) {
                return null;
            }
            myUser.setPassword(passwordEncoder.encode(code));
        } else {
            myUser = userService.getUserByUsername(username);
        }
        if (null == myUser) {
            return null;
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        List<Permission> permissionList = myUser.getPermissionList();
        //赋予已登录的权限
        grantedAuthorities.add(new SimpleGrantedAuthority("/logined"));
        for (Permission permission : permissionList) {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getUrl());
            grantedAuthorities.add(grantedAuthority);
        }
        return new User(myUser.getUsername(), myUser.getPassword(), grantedAuthorities);
    }
}
